package com.mxf.code.chain_params;

import com.alibaba.fastjson.JSON;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

/**
 * @author 28382
 */
public abstract class DataValidHandler<T> {

    protected DataValidHandler next;


    /**
     * 用于对下一个处理器的引用
     */
    public void setNext(DataValidHandler next) {
        this.next = next;
    }

    /**
     * 其它规则校验
     */
    public Result<Void> ruleVerification(String key, ParamRequest paramRequest) {
        // 默认实现
        return new Result<>();
    }

    private Class<?> getClazz() {
        // 使用反射获取 DataValidHandler 类中声明的泛型类型参数
        Type parameterizedType = this.getClass().getGenericSuperclass();
        return (Class<?>) ((ParameterizedType) parameterizedType).getActualTypeArguments()[0];
    }

    /**
     * 处理
     */
    public final Result<Void> handle(Map<String, ParamRequest> paramMap) {
        Iterator<Map.Entry<String, ParamRequest>> iterator = paramMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, ParamRequest> entry = iterator.next();
            ParamRequest paramRequest = entry.getValue();
            if (Objects.isNull(paramRequest) || (getClazz() != DataTypeEnum.getClazzByCode(paramRequest.getDataType()))) {
                continue;
            }
            if (paramRequest.getValue() != null && !getClazz().isInstance(paramRequest.getValue())) {
                paramMap.clear();
                next = null;
                return new Result<Void>().error("Value of " + entry.getKey() + " is invalid: " + paramRequest.getValue());
            }
            Result<Void> ruleVerificationResult = ruleVerification(entry.getKey(), paramRequest);
            if (ruleVerificationResult.getCode() != 0) {
                paramMap.clear();
                next = null;
                return ruleVerificationResult;
            }
            iterator.remove();
        }

        return nextHandle(paramMap);
    }

    /**
     * @param paramMap 参数列表
     * @return com.mxf.code.chain_params.Result<java.lang.Void>
     * @author mxf
     * @description 下一个处理器
     * @createTime 2023/5/24 10:46
     * @paramType [java.util.Map<java.lang.String, com.mxf.code.chain_params.ParamRequest>]
     */
    public final Result<Void> nextHandle(Map<String, ParamRequest> paramMap) {
        Result<Void> handleResult = new Result<>();
        if (!Objects.isNull(next)) {
            handleResult = next.handle(paramMap);
        } else {
            if (!CollectionUtils.isEmpty(paramMap)) {
                return new Result<Void>().error("存在其它类型参数未被校验：" + JSON.toJSONString(paramMap));
            }
        }
        return handleResult;
    }
}
